<template>
  <div class="seat-container">
    <div class="header">
      <h1>餐厅座位管理</h1>
      <el-button type="primary" @click="refreshSeats">刷新列表</el-button>
    </div>
    
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="座位号">
          <el-input v-model="searchForm.seatNumber" placeholder="请输入座位号" clearable></el-input>
        </el-form-item>
        
        <el-form-item label="区域">
          <el-select v-model="searchForm.area" placeholder="请选择区域" clearable>
            <el-option label="大厅" value="大厅"></el-option>
            <el-option label="包间" value="包间"></el-option>
            <el-option label="吧台" value="吧台"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="可坐人数">
          <el-select v-model="searchForm.capacity" placeholder="请选择人数" clearable>
            <el-option label="1人" value="1"></el-option>
            <el-option label="2人" value="2"></el-option>
            <el-option label="4人" value="4"></el-option>
            <el-option label="6人" value="6"></el-option>
            <el-option label="8人" value="8"></el-option>
            <el-option label="10人" value="10"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="空闲" value="1"></el-option>
            <el-option label="已预订" value="0"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 座位列表 -->
    <div class="seat-list">
      <el-row :gutter="20">
        <el-col 
          :xs="24" :sm="12" :md="8" :lg="6" 
          v-for="seat in seatList" 
          :key="seat.id"
          class="seat-col"
        >
          <div class="seat-card">
            <div class="card-header">
              <span class="seat-number">{{ seat.seatNumber }}</span>
              <el-tag 
                :type="seat.status === 1 ? 'success' : 'danger'" 
                class="status-tag"
              >
                {{ seat.status === 1 ? '空闲' : '已预订' }}
              </el-tag>
            </div>
            
            <div class="seat-info">
              <div class="info-item">
                <i class="el-icon-location-outline"></i>
                <span>{{ seat.area }}</span>
              </div>
              <div class="info-item">
                <i class="el-icon-user"></i>
                <span>可坐 {{ seat.capacity }} 人</span>
              </div>
              <div class="info-item description">
                <i class="el-icon-document"></i>
                <span>{{ seat.description || '暂无描述' }}</span>
              </div>
            </div>
            
            <div class="card-actions">
              <el-button 
                type="primary" 
                size="small" 
                :disabled="seat.status !== 1"
                @click="handleBook(seat)"
              >
                立即预订
              </el-button>
              
              <!-- <el-button 
                size="small" 
                :type="isSeatCollected(seat.id) ? 'success' : 'default'"
                @click="toggleCollection(seat)"
              >
                <i class="el-icon-star-off"></i>
                {{ isSeatCollected(seat.id) ? '已收藏' : '收藏' }}
              </el-button> -->
              <el-button 
                :type="isSeatCollected(seat.id) ? 'success' : 'default'" 
                :icon="isSeatCollected(seat.id) ? 'el-icon-star-on' : 'el-icon-star-off'"
                
                @click="toggleCollection(seat)"
                class="action-btn"
                circle
              >
                {{ isSeatCollected(seat.id) ? '已收藏' : '收藏' }}
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalSeats"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
    
    <!-- 预订对话框 -->
    <el-dialog 
      title="座位预订" 
      :visible.sync="bookDialogVisible" 
      width="30%"
      center
    >
      <el-form :model="bookForm" label-width="100px">
        <el-form-item label="座位号">
          <el-input v-model="bookForm.seatNumber" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="区域">
          <el-input v-model="bookForm.area" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="可坐人数">
          <el-input v-model="bookForm.capacity" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="用餐人数" required>
          <el-input-number 
            v-model="bookForm.peopleCount" 
            :min="1" 
            :max="bookForm.capacity"
          ></el-input-number>
        </el-form-item>
        
        <el-form-item label="预订日期" required>
          <el-date-picker 
            v-model="bookForm.orderDate" 
            type="date" 
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        
        <el-form-item label="预订时间" required>
          <el-time-select
            v-model="bookForm.orderTime"
            :picker-options="{
              start: '08:00',
              step: '00:30',
              end: '22:00'
            }"
            placeholder="选择时间"
          ></el-time-select>
        </el-form-item>
      </el-form>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="bookDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmBook">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listSeat } from '@/api/Seat';
import { addSeatorder , listSeatorder} from '@/api/Seatorder';
import { addCollection, delCollectionInfo ,listCollection} from '@/api/Collection';
import { getToken, getUserId } from '@/utils/auth';

export default {
  name: 'SeatList',
  data() {
    return {
      // 存储现有有效订单
      existingSeats: [],
      // 搜索表单数据
      searchForm: {
        seatNumber: '',
        area: '',
        capacity: '',
        status: ''
      },
      
      // 座位列表数据
      seatList: [],
      totalSeats: 0,
      currentPage: 1,
      pageSize: 8,
      
      // 用户收藏的座位ID列表
      collectedSeats: [],
      
      // 预订对话框相关
      bookDialogVisible: false,
      bookForm: {
        seatId: null,
        seatNumber: '',
        area: '',
        capacity: '',
        peopleCount: 1,
        orderDate: '',
        orderTime: ''
      }
    };
  },
  created() {
    this.fetchSeats();
    this.checkLoginStatus();
    this.fetchCollections();
  },
  mounted(){
    this.fetchCollections();
    this.fetchExistingOrders();
  },
  methods: {
    // 获取现有有效订单
    async fetchExistingOrders() {
      try {
        const response = await listSeatorder();
        if (response.code === 200) {
          // 只保留状态为1（待支付）和2（已支付）的有效订单
          this.existingSeats = response.rows.filter(
            order => order.status === 1 || order.status === 2
          );
        }
      } catch (error) {
        console.error('获取现有订单失败:', error);
        this.$message.error('获取座位预订信息失败，请稍后重试');
      }
    },
    // 获取当前用户的收藏列表
    async fetchCollections() {
      // 检查登录状态
      if (!getToken()) return;
      
      try {
        const userId = getUserId();
        const params = {
          userId,
          itemType: 2 // 2表示座位类型
        };
        
        const response = await listCollection(params);
        this.collectedSeats = response.rows.map(item => item.itemId) || [];
      } catch (error) {
        console.error('获取收藏列表失败:', error);
        this.$message.error('获取收藏列表失败');
      }
    },
    // 检查登录状态
    checkLoginStatus() {
      if (!getToken()) {
        this.$message.warning('请先登录系统');
        this.$router.push('/login');
      }
    },
    
    // 获取座位列表
    async fetchSeats() {
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        };
        
        const response = await listSeat(params);
        if (response.code === 200) {
          this.seatList = response.rows;
          this.totalSeats = response.total;
        } else {
          this.$message.error(response.msg || '获取座位列表失败');
        }
      } catch (error) {
        console.error('获取座位列表失败:', error);
        this.$message.error('获取座位列表失败');
      }
    },
    
    // 处理搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchSeats();
    },
    
    // 重置搜索条件
    resetSearch() {
      this.searchForm = {
        seatNumber: '',
        area: '',
        capacity: '',
        status: ''
      };
      this.currentPage = 1;
      this.fetchSeats();
    },
    
    // 刷新座位列表
    refreshSeats() {
      this.currentPage = 1;
      this.resetSearch();
    },
    
    // 分页处理
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchSeats();
    },
    
    // 打开预订对话框
    handleBook(seat) {
      // 检查登录状态
      if (!getToken()) {
        this.$router.push('/login');
        return;
      }
      this.fetchExistingOrders();
      this.bookForm = {
        seatId: seat.id,
        seatNumber: seat.seatNumber,
        area: seat.area,
        capacity: seat.capacity,
        peopleCount: 1,
        orderDate: '',
        orderTime: ''
      };
      
      this.bookDialogVisible = true;
    },
    
    // 确认预订
    async confirmBook() {
      // 表单验证
      if (!this.bookForm.orderDate || !this.bookForm.orderTime) {
        this.$message.warning('请选择预订日期和时间');
        return;
      }
      
      if (this.bookForm.peopleCount < 1) {
        this.$message.warning('用餐人数至少为1人');
        return;
      }
      // 检查日期和时间冲突
      const selectedDate = this.bookForm.orderDate;
      const selectedTime = this.bookForm.orderTime + ":00"; // 补全时间格式
      const seatId = this.bookForm.seatId;
      
      // 检查当前座位的已有预订是否存在冲突
      const hasConflict = this.existingSeats.some(order => {
        // 只检查相同座位的订单
        if (order.seatId !== seatId) return false;
        // 检查日期是否相同
        if (order.orderDate !== selectedDate) return false;
        
        // 检查时间是否冲突（默认每个预订占用0.5小时）
        const existingTime = new Date(`1970-01-01T${order.orderTime}`);
        const selectedDateTime = new Date(`1970-01-01T${selectedTime}`);
        // 计算时间差（分钟）
        const timeDiff = Math.abs(selectedDateTime - existingTime) / (1000 * 60);
        // 如果两个预订时间间隔小于0.5小时，则视为冲突
        return timeDiff < 30;
      });
      
      if (hasConflict) {
        this.$message.error('该座位在选定的日期和时间已被预订，请选择其他时间');
        return;
      }
      try {
        const orderData = {
          id:null,
          userId: getUserId(),
          seatId: this.bookForm.seatId,
          orderDate: this.bookForm.orderDate,
          orderTime: this.bookForm.orderTime+":00",
          peopleCount: this.bookForm.peopleCount
        };
        
        const response = await addSeatorder(orderData);
        if (response.code === 200) {
          
          this.$message.success('预订成功');
          this.bookDialogVisible = false;
          this.fetchSeats(); // 刷新列表更新座位状态
        } else {
          this.$message.error(response.msg || '预订失败');
        }
        
      } catch (error) {
        console.error('预订失败:', error);
        this.$message.error(`预订失败: ${error.message || '请稍后重试'}`);
      } finally {
        this.fetchSeats();  // 刷新列表更新座位状态
      }
    },
    
    // 检查座位是否已被收藏
    isSeatCollected(seatId) {
      return this.collectedSeats.includes(seatId);
    },
    
    // 切换收藏状态
    async toggleCollection(seat) {
      // 检查登录状态
      if (!getToken()) {
        this.$router.push('/login');
        return;
      }
      
      const seatId = seat.id;
      const userId = getUserId();
      
      try {
        if (this.isSeatCollected(seatId)) {
          // 取消收藏
          const response = await delCollectionInfo({
            userId,
            itemId: seatId,
            itemType: 2 // 2代表座位类型
          });
          
          if (response.code === 200) {
            this.collectedSeats = this.collectedSeats.filter(id => id !== seatId);
            this.$message.success('已取消收藏');
          } else {
            this.$message.error(response.msg || '取消收藏失败');
          }
        } else {
          // 添加收藏
          const collectionData = {
            userId,
            itemType: 2, // 2代表座位类型
            itemId: seatId
          };
          
          const response = await addCollection(collectionData);
          if (response.code === 200) {
            this.collectedSeats.push(seatId);
            this.$message.success('收藏成功');
          } else {
            this.$message.error(response.msg || '收藏失败');
          }
        }
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('操作失败');
      }
    }
  }
};
</script>

<style scoped>
.seat-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.header h1 {
  color: #303133;
  font-size: 24px;
  margin: 0;
}

.search-section {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.seat-list {
  margin-top: 20px;
}

.seat-col {
  margin-bottom: 20px;
}

.seat-card {
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  overflow: hidden;
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.seat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px 0 rgba(0,0,0,0.15);
}

.card-header {
  background: #409EFF;
  color: white;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.seat-number {
  font-size: 20px;
  font-weight: bold;
}

.status-tag {
  font-weight: bold;
}

.seat-info {
  padding: 20px;
  flex-grow: 1;
}

.info-item {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.info-item i {
  margin-right: 10px;
  font-size: 16px;
  color: #409EFF;
}

.description {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.card-actions {
  padding: 0 20px 20px;
  display: flex;
  justify-content: space-between;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }
  
  .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
  }
  
  .card-actions {
    flex-direction: column;
    gap: 10px;
  }
  
  .card-actions .el-button {
    width: 100%;
  }
}
</style>